#!/usr/bin/env python

import time
import urllib

import templess
import httplib2
import elementtree.ElementTree as ET
import id3reader

USERNAME = 'dealmeida'
PASSWORD = 'mozart'
CONFIG   = '/Users/roberto/Music/iTunes/iTunes Music Library.xml'
SONGS    = 20
ALBUM    = 'iRATE songs'

TREE = """<?xml version="1.0" encoding="UTF-8"?>
<TrackDatabase xmlns:t="http://johnnydebris.net/xmlns/templess" serial="10">
    <User host="server.irateradio.org" port="2278" t:attr="name name; password password"/>

    <Tracks t:replace="tracks">
        <Track t:attr="rating rating; played played; last last; weight weight; volume volume; state state; broken broken; artist artist; title title; url url; file file"/>
    </Tracks>
</TrackDatabase>"""

FEED = """<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:t="http://johnnydebris.net/xmlns/templess" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">

<channel>
    <title t:content="album"/>

    <item t:content="tracks">
        <title t:content="title"/>
        <itunes:author t:content="artist"/>
        <enclosure t:attr="url url; length length; type type"/>
        <pubDate t:content="now"/>
    </item>

</channel>
</rss>
"""


def parse_itunes_xml(filepath):
    tree = ET.parse(filepath)
    tracks = tree.findall('dict/dict/dict')
    tracks = [[child.text for child in track.getchildren()] for track in tracks]
    tracks = [zip(track[::2], track[1::2]) for track in tracks]
    tracks = [dict(track) for track in tracks]
    tracks = [track for track in tracks if track['Album'] == ALBUM]
    tracks = [fix(track) for track in tracks]
    return tracks

def fix(track):
    fixed = {
             'artist': track.get('Artist'),
             'title' : track.get('Name'),
             'rating': track.get('Rating') and float(track['Rating'])/10.0,
             'played': track.get('Play Count'),
             'last'  : track.get('Play Date UTC') and \
                           time.strftime("%Y%m%d%H%M%S",
                               time.strptime(track['Play Date UTC'], '%Y-%m-%dT%H:%M:%SZ')),
             'file'  : urllib.unquote(track.get('Location')[len('file://localhost'):]),
             'weight': None,
             'volume': None,
             'state' : None,
             'broken': None,
            }
    # Get URL.
    reader = id3reader.Reader(fixed['file'])
    fixed['url'] = reader.getValue('TID') or reader.getValue('TGID')
    return fixed

def get_recommendations(body):
    h = httplib2.Http()

    tracks = []
    while len(tracks) < SONGS:
        try:
            resp, content = h.request("http://server.irateradio.org:2278/", "GET", body=body)
            tree = ET.fromstring(content)
            track = tree.find('Track')
            track = dict(track.items())
            track['now'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())

            # Check file.
            resp, content = h.request(track['url'], "HEAD")
            if resp['status'] == '200':
                track['length'] = resp.get('content-length')
                track['type'] = resp.get('content-type', 'audio/mpeg')
                tracks.append(track)
        except:
            pass
    return tracks

def build_feed(tracks):
    t = templess.template(FEED)
    context = {'tracks': tracks, 'album': ALBUM}
    body = t.unicode(context).encode('utf-8')
    return body


if __name__ == '__main__':
    import sys

    tracks = parse_itunes_xml(CONFIG)
    t = templess.template(TREE)
    context = {'tracks'  : tracks,
               'name'    : USERNAME,
               'password': PASSWORD,
              }
    body = t.unicode(context).encode('utf-8')
    recommendations = get_recommendations(body)
    feed = build_feed(recommendations)

    sys.stdout.write(feed)
